/*
 * DragBehavior.fx
 *
 * Copyright (c) 2010 Remi Barraquand <dev at barraquand.com>. All rights reserved.
 *
 * This file is part of FxTools
 *
 * FxTools is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FxTools is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FxTools. If not, see <http://www.gnu.org/licenses/>.
 */


package com.barraquand.labs.jfxtools.scene;

import javafx.scene.Node;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.MouseButton;

/**
 * DragBehavior
 *
 * Add a drag behavior to a given node. This method is not really the best
 * since it disable the user with the possility to overide mouse event on the
 * node.... a better option should be provided !
 *
 * @author Remi Barraquand <dev at barraquand.com>
 */

public class DragBehavior {
    public var target: Node;

    var startX = 0.0;
    var startY = 0.0;

    public var dragButton: MouseButton = MouseButton.PRIMARY;
    public var dragOnCtrlDown: Boolean = Boolean.TRUE;
    
    init {
        target.onMousePressed = function(e:MouseEvent):Void {
            var goHead = if (dragOnCtrlDown) then e.controlDown else Boolean.TRUE;
            if( e.button == dragButton and goHead ) {
                startX = e.sceneX-target.translateX;
                startY = e.sceneY-target.translateY;
            }
        }

        target.onMouseDragged = function(e:MouseEvent):Void {
            var goHead = if (dragOnCtrlDown) then e.controlDown else Boolean.TRUE;
            if( ((MouseButton.PRIMARY == dragButton and e.primaryButtonDown)
            or  (MouseButton.SECONDARY == dragButton and e.secondaryButtonDown)
            or  (MouseButton.MIDDLE == dragButton and e.middleButtonDown))
            and goHead ) {
                target.translateX = e.sceneX-startX;
                target.translateY = e.sceneY-startY;
            }
        }
    }
}
